<?php
namespace Mobile\Controller;
use Mobile\Logic\Jssdk;
use Mobile\Model\StoreModel;
class IndexController extends MobileBaseController {
    public function index(){ 
		if(IS_POST && I('action')=='yes'){
			M('tousu')->add([
				'duixiang'=>I('duixiang'),
				'content'=>I('beizhu'),
				'user_id'=>I('user_id'), 
				'pingfen'=>I('pingfen'),
				'add_time'=>time()
			]);
			echo \json_encode([
				'code'=>'200',
				'msg'=>'感谢您给我们的建议！'
			]);
			exit;
		}
		$duixiang=[];
		$duixiang=[
			'kehu'=> M('admin')->where("user_name like '%kefu%'")->select(),
			'siji'=> M('pda')->select()
		];

		$this->assign('duixiang',$duixiang);
		$this->assign('user',session('user'));
        $this->display();
    }
    
    public function bindmerchant(){
      
            $store_id = I('store_id');
            $store = M('store')->where(['store_id'=>$store_id])->find();
            if(empty($store)){
                echo '信息错误';
                die;
            }
            $user = M('users')->where(['user_id'=>$store['user_id']])->find();
            if(!empty($user['openid'])){
                echo '已经绑定';
                die;
            }
            $openid = session('wxopenid');
            $unionid = session('wxunionid');
            M('users')->where(['user_id'=>$data['user_id']])->save(['openid'=>$openid,'unionid'=>$unionid]);
	        echo '绑定成功';
	        die;
	        
    }
	
	public function zhuanpan(){
		$lipin=M('zhuanpan')->where('title !=""')->select();
		
		if(IS_POST && $_GET['action']=='zp_cishu'){
			M('users')->where('user_id='.session('user')['user_id'])->setDec('zp_cishu');
			session('user',M('users')->where('user_id='.session('user')['user_id'])->find()); //更新用户信息
			
			foreach($lipin as $key=>$v){
				$pd=M('zhuanpan_log')->where('user_id='.session('user')['user_id'].' and title !="'.$lipin[0]['title'].'"')->find();
					$jilv.=(!empty($pd)) ? $lipin[0]['jilv'].',' : $v['jilv'].','; //判断礼品是否中完
				
			}
			$jilv=rtrim($jilv,',');  
			M('zhuanpan')->where('title="'.I('lipin').'"')->setInc('overnum'); //更新礼品数量
			echo \json_encode([
				'code'=>'200',
				'cishu'=>session('user')['zp_cishu'],
				'overnum'=>M('zhuanpan')->where('title="'.I('lipin').'"')->getField('overnum'),
				'jilv'=>'['.$jilv.']',
				'msg'=>'感谢您的支持！'
			]);
			exit;
		}
		
		session('user',M('users')->where('user_id='.session('user')['user_id'])->find()); //更新用户信息
		$title=$jilv='';
		foreach($lipin as $key=>$v){
			if(!empty($v['title'])){
				$title.='"'.$v['title'].'",';
				$jilv.=($v['num']<=$v['overnum']) ? '-1,' : $v['jilv'].','; //判断礼品是否中完
				$pic.='<img src="'.$v['pic'].'" id="pic'.$v['id'].'" style="display:none;" />';
			}
		}
		
		$title=rtrim($title,',');$jilv=rtrim($jilv,',');
		$this->assign('user',session('user'));
		$this->assign('lipin',$lipin);
		$this->assign('title',$title);
		$this->assign('jilv',$jilv);
		$this->assign('pic',$pic);
	    $this->display();
	}
	
	public function zhuanpan_log(){
		if(IS_POST && $_GET['action']=='yes'){
			M('zhuanpan_log')->where('user_id='.session('user')['user_id'])->add([
				'user_id'=>session('user')['user_id'],
				'user_name'=>session('user')['nickname'],
				'title'=>I('title'),
				'pic'=>M('zhuanpan')->where('title="'.I('title').'"')->getField('pic'),
				'add_time'=>\time(),
			]);
			
		$lipin=M('zhuanpan')->where('title !=""')->select();
		foreach($lipin as $key=>$v){
			if(!empty($v['title'])){
				$jilv.=($v['num']<=$v['overnum']) ? $lipin[0]['jilv'].',' : $v['jilv'].','; //判断礼品是否中完
			}
		}
		$jilv=rtrim($jilv,',');
			echo \json_encode([
				'code'=>'200',
				'jilv'=>'['.$jilv.']',
				'msg'=>'感谢您的支持！'
			]);
			exit;
		}
            $list = M('zhuanpan_log')->where('user_id='.session('user')['user_id'])->order('id desc')->select();
			foreach($list as $key=>$v){
				$list[$key]['zhuangtai']=$v['status']==0 ? '<span style="color:red">未领取</span>' : '<span style="color:green">已领取</span>';
			}
		$this->assign('list',$list);
	    $this->display();
	}
	
	public function cs(){
		$a=['235423542354','257937457345','223343333'];
		foreach($a as $v){
			$danhaos.='
			'.$v; 
		}
		
		$wx_user = M('wx_user')->find();
		$jssdk = new \Mobile\Logic\Jssdk($wx_user['appid'],$wx_user['appsecret']);
		$wx_content = '订单提交成功!
订单号:'.$danhaos.'
时间：'.date("Y-m-d H:i:s",time()).'
<a href="https://shop.lswjsc.com/index.php/Mobile/Index/" data-miniprogram-appid="wx7c609f6efbc804de" data-miniprogram-path="pages/order/list/list">点击查看详情</a>';
		$jssdk->push_msg('oDSRf6JgnH_G7Ar6RcO_GwWkO6S4',$wx_content);
		$this->display();
	}


    public function usertop(){
        $longhu=tpCache("longhu");

        $now=time();$user=session('user');$mytop=0;$myxiaoshou=0;$chaju1=0;$chaju2=0;$keys=0;
      
        if(!$user){
            redirect('/Mobile/Index/wechat_login_error',5,'页面跳转中...');
        }

        $sql = "SELECT ROUND( sum( a.total_amount ), 0 )  as xiaoshou,a.user_id,b.head_pic,b.nick_name,b.mobile,b.nickname FROM ty_order as a LEFT JOIN ty_users as b ON a.user_id = b.user_id WHERE a.add_time > ".strtotime($longhu['longhu_shijian1'])." AND a.add_time < ".strtotime($longhu['longhu_shijian2'])." and dai_type != 2 AND order_status IN ( 0, 1, 2 ) GROUP BY a.user_id ORDER BY xiaoshou desc LIMIT ".$longhu['longhu_num'];
          
        $user_list= M()->query($sql);


//        $my_user=M('users a')
//            ->field('a.head_pic,a.user_id,a.mobile,a.nickname,(select ROUND(sum(order_amount),0) from ty_order where dai_type != 1 and add_time>'.strtotime($longhu['longhu_shijian1']).' and add_time<'.strtotime($longhu['longhu_shijian2']).' and user_id='.$user['user_id'].' and order_status in(0,1,2)) as xiaoshou')
//            ->where(['a.user_id'=>$user['user_id']])
//            ->order('xiaoshou desc')
//            ->find();
        $stat_time = strtotime($longhu['longhu_shijian1']);
        $end_time = strtotime($longhu['longhu_shijian2']);
        // $whereb = "a.addtime > ".strtotime($longhu['longhu_shijian1'])." and  b.is_lock=0 and  a.addtime < ".strtotime($longhu['longhu_shijian2']);
        $whereb="a.addtime>$stat_time and a.addtime<$end_time and b.is_lock=0";
        $sql2 = "SELECT ROUND( sum( a.total_amount ), 0 )  as xiaoshou,a.user_id,b.head_pic,b.nick_name,b.mobile,b.nickname FROM ty_order as a LEFT JOIN ty_users as b ON a.user_id = b.user_id WHERE add_time > ".strtotime($longhu['longhu_shijian1'])." AND add_time < ".strtotime($longhu['longhu_shijian2'])." and dai_type != 2 AND order_status IN ( 0, 1, 2 ) AND a.user_id = ".$user['user_id']." ";
        $my_user= M()->query($sql2);
        //获取我的退货
         $mytuikuan=M('return_goods a')
    		->field("SUM(((a.member_goods_price+a.yijia)*a.goods_num)) as sum,a.*,b.company,b.nickname,b.mobile,b.biaoshi_xian")
    		->join('ty_users b on a.user_id=b.user_id')
    		->where($whereb.' and b.user_id='.$user['user_id'])->find();

         foreach($user_list as $key=>$v){
            
            $tuikuan=M('return_goods a')
    		->field("SUM(((a.member_goods_price+a.yijia)*a.goods_num)) as sum,a.*,b.company,b.nickname,b.mobile,b.biaoshi_xian")
    		->join('ty_users b on a.user_id=b.user_id')
    		->where($whereb.' and b.user_id='.$v['user_id'])->find();
            $user_list[$key]['return_goods_price'] = $tuikuan['sum'];
            $user_list[$key]['xiaoshou'] = $v['xiaoshou']-$tuikuan['sum'];
        }
        usort($user_list, function($a, $b) {
            return $b['xiaoshou'] <=> $a['xiaoshou'];
        });
        foreach($user_list as $key=>$v){
            $ii=$key+1;$keys=$key;
            if($user['user_id']==$v['user_id']){
                $mytop=$ii;
                $myxiaoshou=$v['xiaoshou'];
                break;
            }else{
                $mytop='>'.$longhu['longhu_num'];
            }
        }
        if($user_list[0]['xiaoshou']!=$myxiaoshou){
            $chaju1=$user_list[$keys-1]['xiaoshou']-$myxiaoshou;
            if(!$myxiaoshou){
                $chaju1 = $user_list[$longhu['longhu_num']-1]['xiaoshou'];
            }
            $chaju2=$myxiaoshou-$user_list[$keys+1]['xiaoshou'];

        }else{
            $chaju2=$myxiaoshou-$user_list[$keys+1]['xiaoshou'];
        }
        $this->assign('user_list',$user_list);
        $this->assign('longhu',$longhu);
        $this->assign('mytop',$mytop);
        $this->assign([
            'chaju1'=>$chaju1,
            'chaju2'=>$chaju2,
            'xuzhi'=>$longhu['xuzhi'],
            'lipin'=>$longhu['lipin'],
            'myxiaoshou' =>$my_user[0]['xiaoshou']-$mytuikuan['sum']
        ]);
             
        $this->display();
    }

    /**
     * 获取jdk信息
     */
	public function wx_jdk()
    {
        $weixin_config = M('wx_user')->find(); //获取微信配置
        $jssdk = new Jssdk($weixin_config['appid'],$weixin_config['appsecret']);
//        $jssdk = new Jssdk('wx162fb75bc2fed9f2','5e25ac576489e2009215031be50c8325');
        $res = $jssdk->getSignPackage();
        exit(json_encode($res));
    }
} 